package io.halo.payment.modules.app.ctrl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.halo.payment.common.utils.R;
import io.halo.payment.constants.WxPayConst;
import io.halo.payment.github.wxpay.sdk.WXPayUtil;
import io.halo.payment.modules.app.model.HaloPaymentOrder;
import io.halo.payment.modules.app.service.HaloPaymentOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Writer;
import java.util.Map;

/**
 * 订单
 *
 * @author: austin
 * @since: 2022/12/30 22:09
 */
@Slf4j
@RestController
@RequestMapping("/app/pay")
@Api("订单业务相关接口")
public class HaloPaymentNoticeController {

    @Autowired
    private HaloPaymentOrderService haloPaymentOrderService;

    @PostMapping(value = "/notice")
    @ApiOperation(value = "订单支付回调")
    public R notice(HttpServletRequest request, HttpServletResponse response) throws Exception {

        request.setCharacterEncoding("UTF-8");
        BufferedReader reader = request.getReader();
        String line = reader.readLine();
        StringBuffer temp = new StringBuffer();
        while (StringUtils.isNotBlank(line)) {
            temp.append(line);
            line = reader.readLine();
        }
        reader.close();
        Map<String, String> map = WXPayUtil.xmlToMap(temp.toString());
        //提取响应码和响应信息
        String returnCode = map.get("return_code");
        String returnMsg = map.get("return_msg");
        if (WxPayConst.SUCCESS.equals(returnCode) && WxPayConst.OK.equals(returnMsg)) {
            // 获取订单流水号、订单ID，修改订单状态
            String outTradeNo = map.get("out_trade_no");
            UpdateWrapper<HaloPaymentOrder> wrapper = new UpdateWrapper<>();
            wrapper.eq("code", outTradeNo);
            wrapper.set("status", 2);
            haloPaymentOrderService.update(wrapper);

            //给微信平台一个响应
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/xml");
            Writer writer = response.getWriter();
            BufferedWriter bufferedWriter = new BufferedWriter(writer);
            bufferedWriter.write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
            bufferedWriter.close();
            writer.close();
        }

        return R.ok("订单支付回调成功!");
    }
}
